<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>北京旅游地图 - 个性化旅游系统</title>
    <link rel="stylesheet" href="/static/styles/map.css">
    <!-- 百度地图API -->
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=YWYhzv8agmWHMH3YXoHBAJIIDQfiUAzY"></script>
    <style>
        body, html {
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
        }
        #map-container {
            height: 100%;
            width: 100%;
        }
        .place-info {
            padding: 10px;
            border-radius: 5px;
            background: white;
            box-shadow: 0 2px 6px rgba(0,0,0,0.3);
            max-width: 300px;
        }
        .place-info h3 {
            margin-top: 0;
            color: #333;
        }
        .place-info .popularity {
            color: #ff6600;
            font-weight: bold;
        }
        .place-info .rating {
            color: #f4b400;
        }
        /* 添加样式：推荐地点列表 */
        #sidebar {
            position: absolute;
            top: 10px;
            right: 10px;
            width: 280px;
            background: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            z-index: 100;
            border-radius: 4px;
            overflow: hidden;
        }
        #recommendations {
            padding: 10px;
        }
        #recommendations h3 {
            margin-top: 0;
            margin-bottom: 10px;
            color: #333;
        }
        #recommend-sort {
            width: 100%;
            margin-bottom: 10px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .recommend-item {
            padding: 10px;
            margin-bottom: 6px;
            border-radius: 4px;
            cursor: pointer;
            transition: background 0.3s;
            border-left: 4px solid #28a745;
            background: #f8f9fa;
        }
        .recommend-item:hover {
            background: #e9ecef;
        }
        .recommend-item .name {
            font-weight: bold;
            color: #333;
        }
        .recommend-item .type {
            font-size: 12px;
            color: #666;
        }
        .recommend-item .score {
            margin-top: 4px;
            font-size: 13px;
        }
    </style>
</head>
<body>
    <div id="map-container"></div>
    <div id="place-details" class="place-info" style="display: none;"></div>
    
    <!-- 添加推荐地点侧边栏 -->
    <div id="sidebar">
        <div id="recommendations">
            <h3>推荐地点</h3>
            <select id="recommend-sort" onchange="loadRecommendedPlaces()">
                <option value="popularity">按热度排序</option>
                <option value="rating">按评价排序</option>
            </select>
            <div id="recommended-places">
                <p>正在加载推荐地点...</p>
            </div>
        </div>
    </div>

    <script>
        // 地图初始化
        let map;
        let markers = [];
        let places = [];
        
        function initMap() {
            // 创建百度地图实例
            map = new BMap.Map("map-container");
            // 设置中心点为北京市中心
            const centerPoint = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(centerPoint, 12);
            
            // 添加缩放控件
            map.addControl(new BMap.NavigationControl());
            map.addControl(new BMap.ScaleControl());
            
            // 加载地点数据
            loadPlaces();
            // 加载推荐地点
            loadRecommendedPlaces();
        }
        
        // 加载地点数据
        function loadPlaces() {
            fetch('/api/places')
                .then(response => response.json())
                .then(data => {
                    console.log('加载了地点数据:', data);
                    places = data.places;
                    setupMapMarkers(places);
                })
                .catch(error => {
                    console.error('加载地点数据失败:', error);
                });
        }
        
        // 设置地图标记
        function setupMapMarkers(places) {
            places.forEach(place => {
                const point = new BMap.Point(place.longitude, place.latitude);
                const marker = new BMap.Marker(point);
                marker.placeId = place.id; // 添加placeId属性
                map.addOverlay(marker);
                markers.push(marker);
                
                // 添加点击事件
                marker.addEventListener('click', function() {
                    showPlaceDetails(place);
                });
            });
        }
        
        // 显示地点详情
        function showPlaceDetails(place) {
            const detailsDiv = document.getElementById('place-details');
            detailsDiv.innerHTML = `
                <h3>${place.name}</h3>
                <p>类型: ${place.type}</p>
                <p class="popularity">热度: <span id="place-popularity-${place.id}">${place.popularity}</span></p>
                <p class="rating">评分: ${place.rating}</p>
                <p>${place.description || '暂无描述'}</p>
                <p>地址: ${place.address || '暂无地址信息'}</p>
            `;
            detailsDiv.style.display = 'block';
            
            // 在适当位置显示详情窗口
            const infoWindow = new BMap.InfoWindow(detailsDiv.innerHTML, {
                width: 300,
                title: place.name,
                enableMessage: false
            });
            
            // 在标记上打开信息窗口
            const point = new BMap.Point(place.longitude, place.latitude);
            map.openInfoWindow(infoWindow, point);
        }
        
        // 跳转到指定地点
        function goToPlace(id, lat, lng, name) {
            // 增加地点热度
            increasePopularity(id);
            
            // 跳转到地点
            var point = new BMap.Point(lng, lat);
            map.centerAndZoom(point, 16);
            
            // 找到对应的标记并显示信息窗口
            const marker = markers.find(m => m.placeId === id);
            if (marker) {
                // 触发点击事件打开信息窗口
                marker.dispatchEvent("click");
            } else {
                // 如果找不到标记，创建新的信息窗口
                const place = places.find(p => p.id === id);
                if (place) {
                    showPlaceDetails(place);
                } else {
                    // 如果找不到地点数据，显示简单信息
                    const infoWindow = new BMap.InfoWindow(`<div><h4>${name}</h4><p>加载详细信息中...</p></div>`);
                    map.openInfoWindow(infoWindow, point);
                    
                    // 加载地点详情
                    fetch(`/api/places/${id}`)
                        .then(response => response.json())
                        .then(place => {
                            places.push(place); // 添加到地点列表
                            showPlaceDetails(place);
                        })
                        .catch(error => {
                            console.error('获取地点详情失败:', error);
                        });
                }
            }
        }
        
        // 加载推荐地点
        function loadRecommendedPlaces() {
            var sortBy = document.getElementById('recommend-sort').value;
            document.getElementById('recommended-places').innerHTML = '<p>正在加载推荐地点...</p>';
            
            fetch(`/api/places/recommend/${sortBy}`)
                .then(response => response.json())
                .then(data => {
                    var recommendedPlaces = data.places;
                    var container = document.getElementById('recommended-places');
                    
                    if (recommendedPlaces.length === 0) {
                        container.innerHTML = '<p>没有推荐地点</p>';
                        return;
                    }
                    
                    var html = '';
                    recommendedPlaces.forEach((place, index) => {
                        var scoreText = sortBy === 'popularity' ? 
                            `热度: ${place.popularity}` : 
                            `评价: ${place.rating.toFixed(1)}`;
                        
                        html += `
                            <div class="recommend-item" onclick="goToPlace(${place.id}, ${place.latitude}, ${place.longitude}, '${place.name}')">
                                <div class="name">${index+1}. ${place.name}</div>
                                <div class="type">${place.type}</div>
                                <div class="score">${scoreText}</div>
                            </div>
                        `;
                    });
                    
                    container.innerHTML = html;
                })
                .catch(error => {
                    console.error('加载推荐地点失败:', error);
                    document.getElementById('recommended-places').innerHTML = '<p>加载推荐地点失败</p>';
                });
        }
        
        // 当用户点击地点列表项时调用此函数
        function increasePopularity(placeId) {
            console.log('正在增加地点热度，ID:', placeId);
            // 发送请求到后端API增加热度
            fetch(`/api/increase_popularity/${placeId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('增加热度请求失败');
                }
                return response.json();
            })
            .then(data => {
                console.log('热度更新成功:', data);
                // 更新UI中显示的热度值
                updatePlacePopularityDisplay(placeId, data.new_popularity);
                // 刷新推荐地点列表
                loadRecommendedPlaces();
            })
            .catch(error => {
                console.error('热度更新错误:', error);
            });
        }
        
        // 更新UI中地点的热度显示
        function updatePlacePopularityDisplay(placeId, newPopularity) {
            // 更新详情窗口中的热度显示
            const popularityElement = document.getElementById(`place-popularity-${placeId}`);
            if (popularityElement) {
                popularityElement.textContent = newPopularity;
            }
            
            // 更新地点数据
            for (let i = 0; i < places.length; i++) {
                if (places[i].id === placeId) {
                    places[i].popularity = newPopularity;
                    break;
                }
            }
        }
        
        // 页面加载完成后初始化地图
        window.onload = initMap;
    </script>
</body>
</html> 